package com.novabluetooth.services.bluetooth2;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class HBThread extends Thread {

	// 0X53 4E 06 00 02 04 00 00 0c 读数据
	//0x42,0x34,0x04,0xFF,0xFF,0x02,0x04
	public static final byte[] BG_LAST = new byte[] { (byte) 0x42, (byte) 0x34, (byte) 0x04, (byte) 0xFF, (byte) 0xFF,
			(byte) 0x02, (byte) 0x04};

	// 0X53 4E 06 00 02 0B 00 00 13 关机
	//0x42,0x34,0x04,0xFF,0xFF,0x05,0x07
	public static final byte[] BG_ABORT = new byte[] { (byte) 0x42, (byte) 0x34, (byte) 0x04, (byte) 0xFF, (byte) 0xFF,
			(byte) 0x05, (byte) 0x07};

	private BluetoothSocket bgSocket;
	private Handler bgHandler;
	private InputStream bgInStream;
	private OutputStream bgOutStream;

	public HBThread(BluetoothSocket bluetoothSocket, Handler handler) {
		this.bgHandler = handler;
		this.bgSocket = bluetoothSocket;

		InputStream tmpIn = null;
		OutputStream tmpOut = null;

		try {
			tmpIn = bluetoothSocket.getInputStream();
			tmpOut = bluetoothSocket.getOutputStream();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log.e("LeeTag", "===" + getName() + " tmp create With getStream Error" + e.getMessage());
		}

		bgInStream = tmpIn;
		bgOutStream = tmpOut;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		Log.e("LeeTag", "BGThread run...");
		setName(this.getName());
		if ((bgInStream != null) && (bgOutStream != null)) {
			boolean isRun = true;
			byte[] buffer = new byte[2048];
			int readSize = 0;
			while (isRun) {
				try {
					Log.e("LeeTag", "Write Request Data");

					write(BG_LAST);
					readSize = bgInStream.read(buffer);
					Log.e("LeeTag", "Received Data Length:" + readSize);
					String result = byteArray2HexString(buffer, readSize);
					Log.e("LeeTag", "Received Data: " + result);

					if (bgHandler != null) {
						// bgOutStream.write(BG_ABORT);
						/*
						 * Thread.sleep(500); bgOutStream.write(BG_ABORT);
						 * Thread.sleep(500); bgOutStream.write(BG_ABORT);
						 * Thread.sleep(1000); bgOutStream.write(BG_ABORT);
						 */
						bgInStream.close();
						bgOutStream.close();
						bgInStream = null;
						bgOutStream = null;
						 if (result.contains("HB") && result.contains("HCT"))
		                    {
		                        //m_SerialPort.DataReceived -= m_SerialPort_DataReceived;


		                        int hb = result.indexOf("HB");
		                        String[] strHB = result.substring(hb, 12).split(":");
		                        int hct = result.indexOf("HCT");
		                        String[] strHCT = result.substring(hct).split(":");
		                        String HB = null;
		                        String HTC=null;
		                        if (strHB != null && strHB.length > 1)
		                        {
		                            HB = strHB[1].replace("g/dL", "").trim();
		                        }
		                        if (strHCT != null && strHCT.length > 1)
		                        {
		                            HTC = strHCT[1].trim();
		                        }
		                        Bundle bundle = new Bundle();
								String address = bgSocket.getRemoteDevice().getAddress();
								bundle.putString(BGResultActivity.BG_ADDR, address);
								bundle.putString("deviceType", "NOVAHB");
								float bg=Float.parseFloat(HB);
								
								bundle.putFloat(BGResultActivity.BG, bg);

								Message msg = new Message();
								msg.setData(bundle);
								msg.what = MessageValue.MSG_READ_BG;
								bgHandler.sendMessage(msg);
								isRun = false;
								cancel();
								return;

		                        
		                    }

						

					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					cancel();
					return;
				} 
			}
		}

	}

	public void write(byte[] bytes) {
		try {
			bgOutStream.write(bytes);
			// bgOutStream.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log.e("LeeTag", "=== Write Exception:" + e.getMessage());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log.e("LeeTag", "===  Exception:" + e.getMessage());
		}
	}

	private void cancel() {
		if (bgSocket != null) {
			try {
				// Thread.sleep(100);
				bgSocket.close();
				bgSocket = null;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public static String byteArray2HexString(byte[] bytes, int byteSize) {
		byte[] buf = bytes;
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < byteSize; i++) {
			String str = Integer.toHexString(buf[i] & 0xFF);
			if (str.length() < 2) {
				str = '0' + str;
			}
			str = str.toUpperCase();
			sb.append(str);
		}

		return sb.toString();
	}
}
